package com.niubi.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.niubi.yygh.common.result.R;
import com.niubi.yygh.model.user.UserInfo;
import com.niubi.yygh.user.service.UserInfoService;
import com.niubi.yygh.user.util.ConstantPropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.HttpClientUtils;
import util.JwtHelper;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/user/wx")
public class WeixinApiController {

  @Autowired
  private UserInfoService userInfoService;
  @Autowired
  private RedisTemplate redisTemplate;

  /**
   * 获取微信登录参数
   */
  @GetMapping("getLoginParam")
  @ResponseBody
  public R genQrConnect() throws UnsupportedEncodingException {
    String appid = ConstantPropertiesUtil.WX_OPEN_APP_ID;
    String scope = "snsapi_login";
    String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
    redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");

    Map<String, Object> map = new HashMap<>();
    map.put("appid", appid);
    map.put("scope", scope);
    map.put("redirectUrl", redirectUrl);
    map.put("state", System.currentTimeMillis());
    return R.ok().data(map);
  }

  @GetMapping("callback")
  public String callback(String code, String state, HttpSession session) {
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ConstantPropertiesUtil.WX_OPEN_APP_ID
//                +"&secret="+ConstantPropertiesUtil.WX_OPEN_APP_SECRET
//                +"&code="+code
//                +"&grant_type=authorization_code";
//        String result = HttpClientUtils.get(url);
    StringBuffer baseAccessTokenUrl = new StringBuffer().append("https://api.weixin.qq.com/sns/oauth2/access_token")
            .append("?appid=%s")
            .append("&secret=%s")
            .append("&code=%s")
            .append("&grant_type=authorization_code");
    String  accessUrl =String.format(baseAccessTokenUrl.toString(),
            ConstantPropertiesUtil.WX_OPEN_APP_ID,
            ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
            code);
    try {
      String resultInfo = HttpClientUtils.get(accessUrl);
      JSONObject jsonObject = JSONObject.parseObject(resultInfo);
      String access_token = jsonObject.getString("access_token");
      String openid = jsonObject.getString("openid");
      StringBuffer userUrl = new StringBuffer()
              .append("https://api.weixin.qq.com/sns/userinfo")
              .append("?access_token=%s")
              .append("&openid=%s");
      String userInfoUrl = String.format(userUrl.toString(),access_token,openid);
      String userInfoResult = HttpClientUtils.get(userInfoUrl);
      JSONObject userInfoObject = JSONObject.parseObject(userInfoResult);
      System.out.println("userInfoResult = " + userInfoResult);
      String nickname = userInfoObject.getString("nickname");
      UserInfo userInfo = userInfoService.selectUserByOpenId(openid);
      if (userInfo==null){
        userInfo = new UserInfo();
        userInfo.setNickName(nickname);
        userInfo.setOpenid(openid);
        userInfo.setStatus(1);
        userInfoService.save(userInfo);
      }
      Map<String,String> map = new HashMap<>();
      //微信扫码后,绑定手机号
      String phone = userInfo.getPhone();
      //判断是否需要绑定
      if (StringUtils.isEmpty(phone)){
        //返回openid
        map.put("openid",userInfo.getOpenid());
      }else {
        map.put("openid","");
      }
      //返回页面显示名称
      String name = userInfo.getName();
      if(StringUtils.isEmpty(name)) {
        name = userInfo.getNickName();
      }
      if(StringUtils.isEmpty(name)) {
        name = userInfo.getPhone();
      }
      map.put("name", name);
      //根据userid和name生成token字符串
      String token = JwtHelper.createToken(userInfo.getId(), name);
      map.put("token", token);
      return "redirect:http://localhost:3000/weixin/callback?token="
              +map.get("token")+
              "&openid=" +map.get("openid")
              +"&name="+URLEncoder.encode(map.get("name"),"utf-8");

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
}